import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import '../../../services/gb_video_service.dart';
import '../../../utils/themes/app_theme_extension.dart';
import '../../../translations/app_translations.dart';

class DeviceVideoPlayView extends StatefulWidget {
  const DeviceVideoPlayView({
    Key? key,
  }) : super(key: key);

  @override
  State<DeviceVideoPlayView> createState() => _DeviceVideoPlayViewState();
}

class _DeviceVideoPlayViewState extends State<DeviceVideoPlayView> {
  final GBVideoService _gbVideoService = Get.find<GBVideoService>();
  final args = Get.arguments as Map<String, dynamic>;
  
  // 状态变量
  bool _isLoading = true;
  bool _isError = false;
  String _errorMessage = '';
  Map<String, dynamic>? _videoInfo;
  bool _isFullScreen = false;
  
  // 按钮状态
  final Map<String, bool> _buttonPressedState = {};
  
  // 视频信息
  late String _deviceName;
  late String _channelName;
  late String _wvpDeviceId;
  late String _channelId;
  
  // 视频播放器
  late final Player _player = Player();
  late final VideoController _videoController = VideoController(_player);
  
  String _currentStreamType = 'hls'; // 默认使用HLS流，兼容性好

  @override
  void initState() {
    super.initState();
    
    _deviceName = args['deviceName'] ?? 'Unknown Device';
    _channelName = args['channelName'] ?? 'Unknown Channel';
    _wvpDeviceId = args['wvpDeviceId'] ?? '';
    _channelId = args['channelId'] ?? '';
    
    debugPrint('初始化视频播放页面');
    debugPrint('设备名称: $_deviceName');
    debugPrint('通道名称: $_channelName');
    debugPrint('设备ID: $_wvpDeviceId');
    debugPrint('通道ID: $_channelId');
    
    _initializeVideoStream();
  }
  
  @override
  void dispose() {
    // 确保退出全屏
    if (_isFullScreen) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, 
        overlays: SystemUiOverlay.values);
    }
    _player.dispose();
    super.dispose();
  }
  
  Future<void> _initializeVideoStream() async {
    if (!mounted) return;
    setState(() {
      _isLoading = true;
      _isError = false;
      _errorMessage = '';
    });
    
    try {
      if (_wvpDeviceId.isEmpty || _channelId.isEmpty) {
        throw Exception(LocaleKeys.getStreamFailed.tr);
      }
      
      final loginSuccess = await _gbVideoService.login('admin', '21232f297a57a5a743894a0e4a801fc3');
      if (!loginSuccess) {
        throw Exception(LocaleKeys.loginVideoFailed.tr);
      }
      
      final videoInfo = await _gbVideoService.startPlay(_wvpDeviceId, _channelId);
      if (videoInfo == null) {
        throw Exception(LocaleKeys.getStreamFailed.tr);
      }
      
      if (!mounted) return;
      setState(() {
        _videoInfo = videoInfo;
      });
      
      await _initializeVideoPlayer();

    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isError = true;
        _errorMessage = e.toString();
      });
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }
  
  Future<void> _initializeVideoPlayer() async {
    final streamUrl = _getStreamUrl(_currentStreamType);
    if (streamUrl == null) {
      throw Exception('${LocaleKeys.getStreamFailed.tr}: $_currentStreamType');
    }
    
    debugPrint('开始播放 $_currentStreamType 流: $streamUrl');
    await _player.open(Media(streamUrl), play: true);
  }
  
  String? _getStreamUrl(String type) {
    if (_videoInfo == null) return null;
    return _videoInfo![type.toLowerCase()];
  }
  
  void _switchStreamType(String type) {
    if (_currentStreamType == type) return;
    
    setState(() {
      _currentStreamType = type;
    });
    
    _initializeVideoPlayer();
  }

  /// 处理云台控制命令
  void _handlePtzCommand(String command, {bool isStop = false}) {
    if (_wvpDeviceId.isEmpty || _channelId.isEmpty) {
      Get.snackbar(LocaleKeys.error.tr, LocaleKeys.getStreamFailed.tr);
      return;
    }

    // 转换命令格式以匹配wvpRequest.js中的格式
    // wvpRequest.js中命令格式为: left/right/up/down/upleft/upright/downleft/downright/zoomin/zoomout/stop
    String normalizedCommand;
    if (isStop) {
      normalizedCommand = "stop";
      
      // 重置按钮状态
      setState(() {
        _buttonPressedState.clear();
      });
    } else {
      switch (command) {
        case "LEFT": normalizedCommand = "left"; break;
        case "RIGHT": normalizedCommand = "right"; break;
        case "UP": normalizedCommand = "up"; break;
        case "DOWN": normalizedCommand = "down"; break;
        case "ZOOMIN": normalizedCommand = "zoomin"; break;
        case "ZOOMOUT": normalizedCommand = "zoomout"; break;
        default: normalizedCommand = command.toLowerCase();
      }
      
      // 设置按钮按下状态
      setState(() {
        _buttonPressedState[command] = true;
      });
    }
    
    debugPrint('发送云台控制命令: $normalizedCommand');
    
    // 设置合理范围内的速度参数
    // 根据错误信息，zoomSpeed必须在0-15范围内
    int horizonSpeed = 50;  // 水平速度
    int verticalSpeed = 50; // 垂直速度
    int zoomSpeed = 5;      // 变焦速度，限制在0-15范围内
    
    // 根据命令类型设置不同的速度，但确保在合理范围内
    if (normalizedCommand == "left" || normalizedCommand == "right") {
      horizonSpeed = 80;    // 左右移动速度
    } else if (normalizedCommand == "up" || normalizedCommand == "down") {
      verticalSpeed = 80;   // 上下移动速度
    } else if (normalizedCommand == "zoomin" || normalizedCommand == "zoomout") {
      zoomSpeed = 10;       // 变焦速度，确保在0-15范围内
    }
    
    _gbVideoService.ptzControl(
      _wvpDeviceId, 
      _channelId, 
      normalizedCommand,
      horizonSpeed: horizonSpeed,
      verticalSpeed: verticalSpeed,
      zoomSpeed: zoomSpeed
    ).then((success) {
      if (!success) {
        debugPrint('云台控制命令 ($normalizedCommand) 发送失败');
      } else {
        debugPrint('云台控制命令 ($normalizedCommand) 发送成功');
      }
    });
  }

  /// 显示视频流信息弹窗
  void _showVideoInfoDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.info_outline, color: Colors.blue[700]),
            const SizedBox(width: 8),
            Text(LocaleKeys.videoInfo.tr),
          ],
        ),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildInfoRow(LocaleKeys.currentPlayingFormat.tr, _currentStreamType.toUpperCase()),
              _buildInfoRow(LocaleKeys.deviceId.tr, _wvpDeviceId),
              _buildInfoRow(LocaleKeys.channelId.tr, _channelId),
              _buildInfoRow(LocaleKeys.deviceName.tr, _deviceName),
              _buildInfoRow(LocaleKeys.channelName.tr, _channelName),
              const Divider(height: 24),
              if (_videoInfo != null) ...[
                _buildInfoRow('FLV', _videoInfo!['flv']?.toString() ?? 'N/A'),
                _buildInfoRow('HLS', _videoInfo!['hls']?.toString() ?? 'N/A'),
                _buildInfoRow('RTMP', _videoInfo!['rtmp']?.toString() ?? 'N/A'),
                _buildInfoRow('RTSP', _videoInfo!['rtsp']?.toString() ?? 'N/A'),
              ]
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(LocaleKeys.close.tr),
          ),
        ],
      ),
    );
  }

  /// 切换全屏模式
  void _toggleFullScreen() {
    setState(() {
      _isFullScreen = !_isFullScreen;
    });

    if (_isFullScreen) {
      // 进入全屏模式
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeRight,
      ]);
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
    } else {
      // 退出全屏模式
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, 
        overlays: SystemUiOverlay.values);
    }
  }

  @override
  Widget build(BuildContext context) {
    debugPrint('构建视频播放页面UI');
    
    if (_isFullScreen) {
      return _buildFullScreenLayout();
    }
    
    return Scaffold(
      appBar: AppBar(
        title: Text('$_deviceName - $_channelName'),
        actions: [
          // 更改为文字边框按钮样式
          Container(
            margin: const EdgeInsets.only(right: 8),
            child: OutlinedButton.icon(
              icon: const Icon(Icons.info_outline, size: 16),
              label: Text(LocaleKeys.details.tr, style: const TextStyle(fontSize: 14)),
              style: OutlinedButton.styleFrom(
                foregroundColor: Colors.blue[700],
                side: BorderSide(color: Colors.blue[700]!),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              onPressed: _showVideoInfoDialog,
            ),
          ),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _initializeVideoStream,
          ),
        ],
      ),
      body: _buildBody(),
    );
  }
  
  /// 构建全屏布局
  Widget _buildFullScreenLayout() {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 视频播放器（全屏）
          Center(
            child: Video(
              controller: _videoController,
              fill: Colors.black,
            ),
          ),
          
          // 右上角返回按钮
          Positioned(
            top: 16,
            right: 16,
            child: ElevatedButton.icon(
              icon: const Icon(Icons.fullscreen_exit),
              label: Text(LocaleKeys.back.tr),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue[700],
                foregroundColor: Colors.white,
              ),
              onPressed: _toggleFullScreen,
            ),
          ),
          
          // 视频控制覆盖层（可选，用于显示播放状态等）
          if (_isLoading)
            const Center(child: CircularProgressIndicator()),
          
          if (_isError)
            Center(
              child: Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(Icons.error_outline, color: Colors.red, size: 48),
                    const SizedBox(height: 16),
                    Text(
                      LocaleKeys.loadingFailed.tr,
                      style: const TextStyle(color: Colors.white, fontSize: 18),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      _errorMessage,
                      style: const TextStyle(color: Colors.white70),
                    ),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _initializeVideoStream,
                      child: Text(LocaleKeys.retry.tr),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
  
  Widget _buildBody() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }
    
    if (_isError) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.error_outline, size: 48, color: Colors.red),
              const SizedBox(height: 16),
              Text(LocaleKeys.loadingFailed.tr, style: Theme.of(context).textTheme.headlineSmall),
              const SizedBox(height: 8),
              Text(_errorMessage, textAlign: TextAlign.center),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _initializeVideoStream,
                child: Text(LocaleKeys.retry.tr),
              ),
            ],
          ),
        ),
      );
    }
    
    debugPrint('构建视频播放和控制UI');
    
    return Column(
      children: [
        // 视频播放区域
        AspectRatio(
          aspectRatio: 16 / 9,
          child: Stack(
            children: [
              Video(
                controller: _videoController,
              ),
              // 全屏按钮
              Positioned(
                bottom: 8,
                right: 8,
                child: IconButton(
                  icon: const Icon(Icons.fullscreen),
                  color: Colors.white,
                  onPressed: _toggleFullScreen,
                ),
              ),
            ],
          ),
        ),
        // 流类型选择器
        _buildStreamTypeSelector(),
        // 内容区域（只保留云台控制）
        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: _buildPtzControls(),
          ),
        ),
      ],
    );
  }
  
  Widget _buildStreamTypeSelector() {
    const streamTypes = ['FLV', 'HLS', 'RTMP', 'RTSP'];
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Row(
          children: streamTypes.map((type) => _buildStreamTypeButton(type, type.toLowerCase())).toList(),
        ),
      ),
    );
  }
  
  Widget _buildStreamTypeButton(String label, String type) {
    final isSelected = _currentStreamType == type;
    final hasUrl = _getStreamUrl(type) != null;
    
    // 使用蓝色，方形按钮
    return Padding(
      padding: const EdgeInsets.only(right: 8),
      child: ElevatedButton(
        onPressed: hasUrl ? () => _switchStreamType(type) : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: isSelected ? Colors.blue[700] : Colors.blue[100],
          foregroundColor: isSelected ? Colors.white : Colors.blue[700],
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4), // 方形按钮
          ),
          elevation: isSelected ? 4 : 1,
        ),
        child: Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
      ),
    );
  }
  
  /// 构建云台控制面板
  Widget _buildPtzControls() {
    debugPrint('构建云台控制面板');
    return Card(
      elevation: 8,
      color: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(
          color: Colors.blue[700]!,
          width: 2,
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(Icons.videocam, color: Colors.blue[700], size: 28),
                const SizedBox(width: 8),
                Text(LocaleKeys.ptzControl.tr, 
                  style: TextStyle(
                    color: Colors.blue[700],
                    fontWeight: FontWeight.bold,
                    fontSize: 22,
                  )
                ),
              ],
            ),
            Divider(height: 24, thickness: 2, color: Colors.blue[100]),
            // 方向控制
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.start, // 改为顶部对齐，修复溢出问题
                children: [
                  // 左侧：变焦控制
                  Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        padding: const EdgeInsets.all(8.0),
                        decoration: BoxDecoration(
                          color: Colors.blue[100],
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Text(
                          LocaleKeys.zoomControl.tr, 
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.blue[800],
                            fontSize: 16,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),
                      _buildLargePtzButton(Icons.zoom_in, "ZOOMIN", LocaleKeys.zoomIn.tr),
                      const SizedBox(height: 24),
                      _buildLargePtzButton(Icons.zoom_out, "ZOOMOUT", LocaleKeys.zoomOut.tr),
                    ],
                  ),
                  
                  // 右侧：方向控制
                  Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        padding: const EdgeInsets.all(8.0),
                        decoration: BoxDecoration(
                          color: Colors.blue[100],
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Text(
                          LocaleKeys.directionControl.tr, 
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.blue[800],
                            fontSize: 16,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),
                      _buildLargePtzButton(Icons.keyboard_arrow_up, "UP", LocaleKeys.up.tr),
                      const SizedBox(height: 8),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          _buildLargePtzButton(Icons.keyboard_arrow_left, "LEFT", LocaleKeys.left.tr),
                          const SizedBox(width: 60),
                          _buildLargePtzButton(Icons.keyboard_arrow_right, "RIGHT", LocaleKeys.right.tr),
                        ],
                      ),
                      const SizedBox(height: 8),
                      _buildLargePtzButton(Icons.keyboard_arrow_down, "DOWN", LocaleKeys.down.tr),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建更大、更明显的云台控制按钮
  Widget _buildLargePtzButton(IconData icon, String command, String label) {
    // 检查按钮是否被按下
    final bool isPressed = _buttonPressedState[command] == true;
    
    return GestureDetector(
      onTapDown: (_) {
        debugPrint('按下 $label 按钮，发送命令: $command');
        _handlePtzCommand(command);
      },
      onTapUp: (_) => _handlePtzCommand(command, isStop: true),
      onLongPressEnd: (_) => _handlePtzCommand(command, isStop: true),
      onTapCancel: () => _handlePtzCommand(command, isStop: true),
      child: Column(
        children: [
          // 使用AnimatedContainer实现按下时的放大效果
          AnimatedContainer(
            duration: const Duration(milliseconds: 150),
            width: isPressed ? 68 : 60,
            height: isPressed ? 68 : 60,
            curve: Curves.easeOut,
            decoration: BoxDecoration(
              color: isPressed ? Colors.blue[900] : Colors.blue[700],
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(isPressed ? 0.4 : 0.3),
                  spreadRadius: isPressed ? 2 : 1,
                  blurRadius: isPressed ? 4 : 3,
                  offset: isPressed ? const Offset(0, 3) : const Offset(0, 2),
                ),
              ],
            ),
            child: Icon(
              icon, 
              size: isPressed ? 42 : 36,
              color: Colors.white,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.blue[800],
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              '$label:',
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          Expanded(
            child: SelectableText(
              value,
              style: TextStyle(color: Colors.blue[700]),
            ),
          ),
        ],
      ),
    );
  }
} 